
import axios from 'axios';
import { Message } from 'element-ui';
import QS from 'qs'
const BASE_URL = 'http://localhost:8090';
// 创建新的axios
const axiosCreate = axios.create({
  withCredentials: false,
  timeout: 1000 * 60,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

// token获取
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axiosCreate.interceptors.request.use(
  config => {
   
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
// 添加响应拦截器
axiosCreate.interceptors.response.use(
  // 请求成功
  res => {

    if (res.status === 200) {
      const code = res.data.code;
      if (code === 200 || code === 100) {
        Promise.resolve(res);
      } else {
        source.cancel();
        errorHandle(res.data.code, res.data.message);
      }
    } else {
      Promise.reject(res);
    }
    return res;
  },
  // 请求失败
  error => {
    const { response } = error;
    if (response) {
      // 请求已发出，但是不在2xx的范围
      Message({
        message: "网络不正常",
        error: 'warning'
      });
      return Promise.reject(response);
    } else {
      // 处理断网的情况
      Message({
        message: "网络不正常",
        error: 'warning'
      });
    }

    return false;
  }
);

const options = {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  // timeout: 1000 * 60
};
const BaseServices = {
  /**
   * post请求方法
   * type = form：form表单格式
   */
  post: async (api, data, type, baseURL = BASE_URL) => {
    try {
      if (type === 'form') {
        options.headers['Content-Type'] = 'multipart/form-data';
      } else if (type === 'json') {
        options.headers['Content-Type'] = 'application/json';
      } else {
        options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
      }
      if (type) {
        options.type = type;
      }
      // data = QS.stringify(data)
      const response = await axiosCreate({ method: 'POST', url: baseURL + api, data, options, headers: options.headers });
      if (response.data) {
        return response.data;
      } else {
        throw new Error('返回数据有误');
      }
    } catch (error) {
      return error;
    }
  },
  // **
  // * put请求方法
  // *
  postGet: async (params, baseURL = BASE_URL) => {
    if (params.method.toLowerCase() === 'get') {
      return BaseServices.get(params.api, params.data || {}, baseURL);
    } else if (params.method.toLowerCase() === 'post') {
      return BaseServices.post(params.api, params.data || {}, params.type, baseURL);
    } else {
      options.headers = { 'Content-Type': 'application/json' };
      try {
        const response = await axiosCreate({
          method: params.method,
          data: params.data || {},
          url: BASE_URL + params.api,
          headers: options.headers
        });

        if (response.data) {
          return response.data;
        } else {
          throw new Error('返回数据有误');
        }
      } catch (error) {
        return error;
      }
    }
  },
  put: async (api, data, type, baseURL = BASE_URL) => {
    try {
      if (type === 'form') {
        options.headers['Content-Type'] = 'multipart/form-data';
      } else if (type === 'json') {
        options.headers['Content-Type'] = 'application/json';
      } else {
        options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
      }
      if (type) {
        options.type = type;
      }
      const response = await axiosCreate({ method: 'PUT', url: baseURL + api, data, options, headers: options.headers });

      if (response.data) {
        return response.data;
      } else {
        throw new Error('返回数据有误');
      }
    } catch (error) {
      return error;
    }
  },
  /**
   * get请求方法
   */
  get: async (api, params = {}, baseURL = BASE_URL) => {
    try {
      const response = await axiosCreate({ method: 'GET', params, url: baseURL + api });

      if (response.data) {
        return response.data;
      } else {
        throw new Error('返回数据有误');
      }
    } catch (error) {
      return error;
    }
  },

  /**
   * 统一请求方法
   * params: 包含四个参数 method（必传）, api（必传）, data, type
   * method：请求格式 大小写都行 POST, GET, PUT, DELETE, PATCH
   * api： 请求路径
   * data：请求参数
   * type：请求文件格式，json，form
   */
  ajax: async (params, baseURL = BASE_URL) => {
    if (params.method.toLowerCase() === 'get') {
      return BaseServices.get(params.api, params.data || {}, baseURL);
    } else if (params.method.toLowerCase() === 'post') {
      return BaseServices.post(params.api, params.data || {}, params.type, baseURL);
    } else if (params.method.toLowerCase() === 'put') {
      return BaseServices.put(params.api, params.data || {}, params.type, baseURL);
    } else {
      options.headers = { 'Content-Type': 'application/json' };
      try {
        const response = await axiosCreate({
          method: params.method,
          data: params.data || {},
          url: BASE_URL + params.api,
          headers: options.headers
        });

        if (response.data) {
          return response.data;
        } else {
          throw new Error('返回数据有误');
        }
      } catch (error) {
        return error;
      }
    }
  },

};

export default BaseServices;
